import { type Ref, onUnmounted } from "vue";
import * as THREE from 'three';
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import Stats from 'three/examples/jsm/libs/stats.module.js'; // 导入 Stats

export function useThree(containerRef: Ref<HTMLElement | null>) {
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
    const renderer = new THREE.WebGLRenderer({ antialias: true });

    let controls: OrbitControls | null = null;
    let animationId: number | null = null;

    const stats = new Stats();
    stats.showPanel(0); // 0: FPS, 1: MS, 2: MB

    const init = () => {
        if (!containerRef.value) return;
        containerRef.value.appendChild(stats.dom);
        // 设置渲染容器
        renderer.setSize(containerRef.value.clientWidth, containerRef.value.clientHeight)
        renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
        containerRef.value.appendChild(renderer.domElement);

        // 设置相机位置
        camera.position.z = 5;

        // 添加控制器
        controls = new OrbitControls(camera, renderer.domElement);
        controls.enableDamping = true

        // 6. 监听控制器变化，更新物体旋转
        controls.addEventListener("change", () => {
            if (!cube || !controls) return;

            // 将控制器的旋转角度同步到物体
            cube.rotation.x = controls.getPolarAngle() - Math.PI / 2; // 俯仰角（上下）
            cube.rotation.y = controls.getAzimuthalAngle(); // 偏航角（左右）
        });

        // 添加物体
        const geometry = new THREE.BoxGeometry(1, 1, 1);
        const material = new THREE.MeshPhongMaterial({ color: 0xffffff,specular: 0x444444,  });
        const cube = new THREE.Mesh(geometry, material);
        scene.add(cube);

        // 开始动画循环
        animate();
    };

    const animate = () => {
        animationId = requestAnimationFrame(animate);
        controls?.update();
        renderer.render(scene, camera);
    };

    const onResize = () => {
        if (!containerRef.value) return;
        camera.aspect = containerRef.value.clientWidth / containerRef.value.clientHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(containerRef.value.clientWidth, containerRef.value.clientHeight);
    };

    const dispose = () => {
        if (animationId) cancelAnimationFrame(animationId);
        controls?.dispose();
        renderer.dispose();
        if (containerRef.value && renderer.domElement) {
            containerRef.value.removeChild(renderer.domElement);
        }
        if (stats.dom && stats.dom.parentNode) {
            stats.dom.parentNode.removeChild(stats.dom);
        }
    };

    // 强制场景更新方法
    const forceUpdate = () => {
        renderer.render(scene, camera);
    };

    onUnmounted(dispose)

    return {
        init,
        onResize,
        dispose,
        forceUpdate,
        scene
    };
}